// 欢迎卡片生成器 - 纯JavaScript实现（移动端优化版）
class WelcomeCardGenerator {
    constructor() {
        this.imageUpload = document.getElementById('imageUpload');
        this.numberInput = document.getElementById('numberInput');
        this.nameInput = document.getElementById('nameInput');
        this.generateBtn = document.getElementById('generateBtn');
        this.downloadBtn = document.getElementById('downloadBtn');
        this.cardCanvas = document.getElementById('cardCanvas');
        this.cardSection = document.getElementById('cardSection');
        this.imagePreview = document.getElementById('imagePreview');
        
        this.ctx = this.cardCanvas.getContext('2d');
        this.uploadedImage = null;
        
        // 移动端Canvas尺寸适配
        this.adjustCanvasSize();
        
        this.initEventListeners();
        // 监听窗口大小变化
        window.addEventListener('resize', () => this.adjustCanvasSize());
        // 监听横竖屏切换
        window.addEventListener('orientationchange', () => {
            setTimeout(() => this.adjustCanvasSize(), 100);
        });
    }
    
    // 移动端Canvas尺寸适配（高分辨率优化）
    adjustCanvasSize() {
        const isMobile = window.innerWidth <= 768;
        const maxWidth = Math.min(window.innerWidth - 40, 800); // 限制最大宽度
        const aspectRatio = 16 / 9; // 保持16:9比例
        
        // 获取设备像素比
        const dpr = window.devicePixelRatio || 1;
        
        let displayWidth, displayHeight;
        
        if (isMobile) {
            // 移动端：根据屏幕宽度自适应
            displayWidth = maxWidth;
            displayHeight = maxWidth / aspectRatio;
        } else {
            // 桌面端：固定尺寸
            displayWidth = 800;
            displayHeight = 450;
        }
        
        // 设置Canvas的显示尺寸（CSS尺寸）
        this.cardCanvas.style.width = displayWidth + 'px';
        this.cardCanvas.style.height = displayHeight + 'px';
        
        // 设置Canvas的实际绘制尺寸（考虑设备像素比）
        this.cardCanvas.width = Math.floor(displayWidth * dpr);
        this.cardCanvas.height = Math.floor(displayHeight * dpr);
        
        // 缩放Canvas上下文以匹配高分辨率
        this.ctx.scale(dpr, dpr);
    }
    
    initEventListeners() {
        // 图片上传事件
        this.imageUpload.addEventListener('change', (e) => {
            this.handleImageUpload(e);
        });
        
        // 生成按钮事件（支持触摸）
        this.generateBtn.addEventListener('click', () => {
            this.generateCard();
        });
        this.generateBtn.addEventListener('touchend', (e) => {
            e.preventDefault();
            this.generateCard();
        });
        
        // 下载按钮事件（支持触摸）
        this.downloadBtn.addEventListener('click', () => {
            this.downloadCard();
        });
        this.downloadBtn.addEventListener('touchend', (e) => {
            e.preventDefault();
            this.downloadCard();
        });
        
        // 输入框变化时检查是否可以生成
        [this.imageUpload, this.numberInput, this.nameInput].forEach(input => {
            input.addEventListener('input', () => {
                this.checkGenerateButton();
            });
        });
        
        // 移动端虚拟键盘处理
        this.numberInput.addEventListener('focus', () => {
            setTimeout(() => {
                document.body.style.overflow = 'hidden';
            }, 300);
        });
        
        this.numberInput.addEventListener('blur', () => {
            document.body.style.overflow = '';
        });
        
        this.nameInput.addEventListener('focus', () => {
            setTimeout(() => {
                document.body.style.overflow = 'hidden';
            }, 300);
        });
        
        this.nameInput.addEventListener('blur', () => {
            document.body.style.overflow = '';
        });
        
        // 防止双击缩放
        let lastTouchEnd = 0;
        document.addEventListener('touchend', (event) => {
            const now = (new Date()).getTime();
            if (now - lastTouchEnd <= 300) {
                event.preventDefault();
            }
            lastTouchEnd = now;
        }, false);
    }
    
    handleImageUpload(event) {
        const file = event.target.files[0];
        if (!file) return;
        
        // 检查文件类型
        if (!file.type.match('image.*')) {
            alert('请上传图片文件！');
            return;
        }
        
        const reader = new FileReader();
        reader.onload = (e) => {
            this.uploadedImage = new Image();
            this.uploadedImage.onload = () => {
                // 显示图片预览
                this.imagePreview.innerHTML = '';
                const previewImg = document.createElement('img');
                previewImg.src = e.target.result;
                this.imagePreview.appendChild(previewImg);
                this.checkGenerateButton();
            };
            this.uploadedImage.src = e.target.result;
        };
        reader.readAsDataURL(file);
    }
    
    checkGenerateButton() {
        const hasImage = this.uploadedImage !== null;
        const hasNumber = this.numberInput.value.trim() !== '';
        const hasName = this.nameInput.value.trim() !== '';
        
        this.generateBtn.disabled = !(hasImage && hasNumber && hasName);
    }
    
    generateCard() {
        if (!this.uploadedImage || !this.numberInput.value || !this.nameInput.value) {
            alert('请完成所有输入项！');
            return;
        }
        
        // 显示卡片区域
        this.cardSection.style.display = 'block';
        
        // 获取设备像素比
        const dpr = window.devicePixelRatio || 1;
        const displayWidth = parseInt(this.cardCanvas.style.width);
        const displayHeight = parseInt(this.cardCanvas.style.height);
        
        // 清空画布（使用实际绘制尺寸）
        this.ctx.clearRect(0, 0, this.cardCanvas.width, this.cardCanvas.height);
        
        // 重置变换矩阵并重新缩放
        this.ctx.setTransform(1, 0, 0, 1, 0, 0);
        this.ctx.scale(dpr, dpr);
        
        // 绘制卡片背景
        this.drawCardBackground(displayWidth, displayHeight);
        
        // 绘制用户图片
        this.drawUserImage(displayWidth, displayHeight);
        
        // 绘制欢迎文字
        this.drawWelcomeText(displayWidth, displayHeight);
        
        // 绘制编号
        this.drawNumber(displayWidth, displayHeight);
        
        // 滚动到卡片区域
        this.cardSection.scrollIntoView({ behavior: 'smooth' });
    }
    
    drawCardBackground(displayWidth, displayHeight) {
        // 创建渐变背景（使用显示尺寸）
        const gradient = this.ctx.createLinearGradient(0, 0, displayWidth, displayHeight);
        gradient.addColorStop(0, '#4facfe');
        gradient.addColorStop(1, '#00f2fe');
        
        // 绘制圆角矩形背景
        this.ctx.fillStyle = gradient;
        this.roundRect(this.ctx, 0, 0, displayWidth, displayHeight, 20);
        this.ctx.fill();
        
        // 添加阴影效果
        this.ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
        this.ctx.shadowBlur = 10;
        this.ctx.shadowOffsetX = 5;
        this.ctx.shadowOffsetY = 5;
    }
    
    drawUserImage(displayWidth, displayHeight) {
        if (!this.uploadedImage) return;
        
        // 根据显示尺寸动态计算图片大小（使用显示尺寸而不是Canvas像素尺寸）
        const isMobile = window.innerWidth <= 768;
        const imageSize = isMobile ? displayWidth * 0.15 : 120;
        const margin = isMobile ? displayWidth * 0.04 : 30;
        
        // 保存当前状态
        this.ctx.save();
        
        // 创建圆形裁剪区域
        this.ctx.beginPath();
        this.ctx.arc(margin + imageSize/2, margin + imageSize/2, imageSize/2, 0, Math.PI * 2);
        this.ctx.closePath();
        this.ctx.clip();
        
        // 绘制图片（使用显示尺寸）
        this.ctx.drawImage(
            this.uploadedImage,
            margin, margin,
            imageSize, imageSize
        );
        
        // 恢复状态
        this.ctx.restore();
        
        // 添加圆形边框
        this.ctx.strokeStyle = 'white';
        this.ctx.lineWidth = isMobile ? 2 : 3;
        this.ctx.beginPath();
        this.ctx.arc(margin + imageSize/2, margin + imageSize/2, imageSize/2, 0, Math.PI * 2);
        this.ctx.stroke();
    }
    
    drawWelcomeText(displayWidth, displayHeight) {
        const name = this.nameInput.value.trim();
        const isMobile = window.innerWidth <= 768;
        
        // 设置文字样式
        this.ctx.fillStyle = 'white';
        this.ctx.textAlign = 'center';
        this.ctx.textBaseline = 'middle';
        
        // 增大移动端字体尺寸，优化手机用户体验
        const mainFontSize = isMobile ? Math.max(displayWidth * 0.08, 32) : 48; // 最小32px，最大8%宽度
        const subFontSize = isMobile ? Math.max(displayWidth * 0.045, 18) : 24;  // 最小18px，最大4.5%宽度
        
        // 绘制主标题
        this.ctx.font = `bold ${mainFontSize}px "Microsoft YaHei", Arial, sans-serif`;
        
        // 检查文字是否过长需要换行
        const welcomeText = `欢迎 ${name}！`;
        const textWidth = this.ctx.measureText(welcomeText).width;
        const maxWidth = displayWidth * 0.85; // 稍微减小最大宽度，为更大字体留空间
        
        if (textWidth > maxWidth && isMobile) {
            // 如果文字太长，分成两行显示
            this.ctx.fillText('欢迎', displayWidth / 2, displayHeight / 2 - mainFontSize/1.5);
            this.ctx.fillText(`${name}！`, displayWidth / 2, displayHeight / 2 + mainFontSize/3);
        } else {
            this.ctx.fillText(welcomeText, displayWidth / 2, displayHeight / 2);
        }
        
        // 绘制副标题
        this.ctx.font = `bold ${subFontSize}px "Microsoft YaHei", Arial, sans-serif`;
        this.ctx.fillText('来到牛客创作天团', displayWidth / 2, displayHeight / 2 + (isMobile ? mainFontSize * 0.8 : 50));
    }
    
    drawNumber(displayWidth, displayHeight) {
        const number = this.numberInput.value.trim();
        const isMobile = window.innerWidth <= 768;
        
        // 设置编号样式，增大移动端字体
        this.ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
        const fontSize = isMobile ? Math.max(displayWidth * 0.035, 16) : 20; // 最小16px，最大3.5%宽度
        this.ctx.font = `bold ${fontSize}px "Microsoft YaHei", Arial, sans-serif`;
        this.ctx.textAlign = 'right';
        this.ctx.textBaseline = 'top';
        
        // 在右上角绘制编号（使用显示尺寸）
        const margin = isMobile ? displayWidth * 0.04 : 30;
        this.ctx.fillText(`编号：${number}`, displayWidth - margin, margin);
    }
    
    // 绘制圆角矩形的辅助函数
    roundRect(ctx, x, y, width, height, radius) {
        ctx.beginPath();
        ctx.moveTo(x + radius, y);
        ctx.lineTo(x + width - radius, y);
        ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
        ctx.lineTo(x + width, y + height - radius);
        ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        ctx.lineTo(x + radius, y + height);
        ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
        ctx.lineTo(x, y + radius);
        ctx.quadraticCurveTo(x, y, x + radius, y);
        ctx.closePath();
    }
    
    downloadCard() {
        if (!this.uploadedImage) {
            return;
        }
        
        // 创建下载链接
        const dataURL = this.cardCanvas.toDataURL('image/png');
        const link = document.createElement('a');
        link.download = `欢迎卡片_${this.nameInput.value.trim()}.png`;
        link.href = dataURL;
        
        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new WelcomeCardGenerator();
});